



setInterval(() => {
    location.reload();
}, 600000);

function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    };
    return 0;
 }


var auto_get = getQueryString("auto_get");
if(auto_get!="true"){

    // 监听页面加载完成事件，并在加载完成后弹出浮层
    var havepop = false;
    window.addEventListener('load', function() {
        const timerId = setInterval(() => {
            var pic = $(".imgTagWrapper").find("img").attr("src");
            console.log(pic)
            if(pic && havepop==false){
                showPopup(pic);
                havepop = true;
                clearInterval(timerId);
            }
        },1000);
    });
}


function setPicForSearch(){
    console.log("setPicForSearch")
    var picNew = $(".image.selected").find("img").attr("src");
    console.log(picNew)
    $("#pic_for_search").attr("src",picNew);
}

$(function(){
  $('.a-button').on('click', function() {
    setPicForSearch();
  }).on('mouseover', function() {
     setPicForSearch();
  }).on('mouseout', function() {
    setPicForSearch();
  });
});



// 获取数据并更新页面内容
function fetchData() {
    var pic = $("#pic_for_search").attr("src");
    if(!pic){
        alert("图片有误") ;
        return;
    }
    var url = "https://s.1688.com/youyuan/index.htm?url="+pic;
    console.log(url);
    window.open(url);

}

function showPopup(pic) {
  // 创建浮层最外层容器
  var container = document.createElement('div');
  container.id = 'popup-container';

  // 创建浮层内部容器
  var inner = document.createElement('div');
  inner.id = 'popup';
  inner.innerHTML = '<h3>点击搜索按钮1688搜索</h3><p>当前图片<img src='+pic+' width=80 id="pic_for_search" ></p>';

  // 创建关闭按钮
  var closeBtn = document.createElement('button');
  closeBtn.innerHTML = '关闭';
  closeBtn.onclick = function() {
    container.parentNode.removeChild(container);
  };

  // 创建刷新按钮
  var refreshBtn = document.createElement('button');
  refreshBtn.innerHTML = '搜索';
  refreshBtn.onclick = function() {
    fetchData(inner);
  };





  // 把内部容器和按钮添加到最外层容器中
  container.appendChild(inner);
  container.appendChild(closeBtn);
  container.appendChild(refreshBtn);
  //container.appendChild(selectElement);
  //container.appendChild(caijiBtn);

  // 把最外层容器添加到页面中
  document.body.appendChild(container);

  // 设置浮层样式
  var popupContainer = document.getElementById('popup-container');
  var popup = document.getElementById('popup');
  popupContainer.style.position = 'fixed';
  popupContainer.style.right = '5%';
  popupContainer.style.top = '50%';
  popupContainer.style.transform = 'translateY(-50%)';
  popupContainer.style.zIndex = '9999';
  popup.style.backgroundColor = 'lightblue';
  popup.style.padding = '10px';
  popup.style.borderRadius = '10px';
  popup.style.boxShadow = '2px 2px 2px rgba(0,0,0,0.4)';
  closeBtn.style.marginRight = '10px';
  closeBtn.style.backgroundColor = '#ff9797';
  closeBtn.style.border = 'none';
  closeBtn.style.color = '#fff';
  closeBtn.style.padding = '5px 10px';
  closeBtn.style.borderRadius = '5px';
  closeBtn.style.cursor = 'pointer';
  refreshBtn.style.backgroundColor = '#7cd6ff';
  refreshBtn.style.border = 'none';
  refreshBtn.style.color = '#fff';
  refreshBtn.style.padding = '5px 10px';
  refreshBtn.style.borderRadius = '5px';
  refreshBtn.style.cursor = 'pointer';
  refreshBtn.style.marginRight = '10px';

    var select_cate = getCookie("select_cate");
    console.log("select_cate:"+select_cate);
    $.get("https://www.gongrenbao.cn/index.php?c=api/ozon/getmanagecate&url="+location.href, function(data, status) {
      console.log(data);
        if(data.data.have_get=="success"){
            // 创建采集按钮
              var caijiBtn = document.createElement('button');
              caijiBtn.innerHTML = '已采集过';
              caijiBtn.onclick = function() {
                 //fetchDataApi();
              };
            container.appendChild(caijiBtn);
            caijiBtn.style.backgroundColor = '#7cd6ff';
              caijiBtn.style.border = 'none';
              caijiBtn.style.color = '#fff';
              caijiBtn.style.padding = '5px 10px';
              caijiBtn.style.borderRadius = '5px';
              caijiBtn.style.cursor = 'pointer';
            document.body.appendChild(container);
        }else{
            var selectElement = document.createElement('select');
            selectElement.setAttribute("id", "my_cat_select");
            for(k in data.data.list){
                const option1 = document.createElement('option');
                option1.value = data.data.list[k].id;
                option1.text = data.data.list[k].value;
                if(select_cate==data.data.list[k].id){
                    option1.setAttribute("selected", "selected");
                }
                selectElement.appendChild(option1);
            }
            selectElement.addEventListener('change', (event) => {
                console.log(event.target.value);
                setCookie("select_cate",event.target.value,86400*10);
            });

              // 创建采集按钮
              var caijiBtn = document.createElement('button');
              caijiBtn.innerHTML = '采集';
              caijiBtn.onclick = function() {
                 fetchDataApiClick();
              };

             container.appendChild(selectElement);
             container.appendChild(caijiBtn);

              caijiBtn.style.backgroundColor = '#7cd6ff';
              caijiBtn.style.border = 'none';
              caijiBtn.style.color = '#fff';
              caijiBtn.style.padding = '5px 10px';
              caijiBtn.style.borderRadius = '5px';
              caijiBtn.style.cursor = 'pointer';

             document.body.appendChild(container);
        }

    });



}




function fetchDataApiClick(){
    var dataPro = {};
    var pics = [];
    $("body").find(".a-spacing-small.item.imageThumbnail").each(function(e){
        pics.push($(this).find("img").attr("src"));
    })
    console.log("pics:")
    console.log(pics)
    dataPro.pics = pics;//图片
    $("script").each(function(e){
        var scriptData = $(this).html();
         //console.log(scriptData);
        // console.log(pics[0]);

        if(scriptData.indexOf('var obj = A.$.parseJSON') !== -1){
                console.log("match到了 A.$.parseJSON");
                var regex = /A\.(\$\.)?parseJSON\(['"]([\s\S]*)['"]\)/;
                var match = scriptData.match(regex);
                if (match) {
                  try {
                      var matchData = match[2].replace(/\\/g, '');
                      var jsonObj = JSON.parse(matchData);
                      var vidlist=jsonObj.videos;
                      console.log(vidlist); // 打印出解析后的 JavaScript 对象
                      var videos = [];
                      for (var i = 0; i < vidlist.length; i++) {
                        var vidUrl = vidlist[i].url;
                        console.log("url["+i+"]是：" + vidUrl);
                            videos.push(vidUrl)
                      }
                      dataPro.videos = videos;
                    } catch (error) {
                      console.error('Invalid JSON:', error);
                    }

                }
        }

        if (scriptData.indexOf(pics[0]) !== -1) {
           console.log("字符串中包含 'world'");
           //console.log(scriptData);
           var pattern = /'colorImages': \s*(\{[\s\S]*?\}),\n/m; // 匹配 var data = {...}; 的正则表达式
           var match = scriptData.match(pattern); // 在代码块中查找 var data = {...}; 的匹配结果
            console.log(match);
            if (match) {
              var dataStr = match[1].replace(/'/g, '"');; // 取出匹配到的 {...} 部分

              var dataObj = JSON.parse(dataStr); // 将 {...} 解析为 JSON 对象
               console.log(dataObj.initial);
              var picsNew = [];
              for (var element of dataObj.initial) {
                  if(element['hiRes']){
                    picsNew.push(element['hiRes'])
                  }
             }
            console.log(picsNew);
            if(picsNew.length>0){
                dataPro.pics= picsNew.splice(0,pics.length);
                //return false;
            }
           }
        }
    })


    dataPro.detail = $(".a-unordered-list.a-vertical.a-spacing-mini").html();
    dataPro.content = $("#witb-content-list").html();
    dataPro.desc = $(".celwidget.aplus-module.aplus-standard").html();
    if($("#productDescription").html() && $("#productDescription").html().length>500){
        dataPro.desc = $("#productDescription").html();
    }
    dataPro.seller = $("#sellerProfileTriggerId").html();
    dataPro.seller_url = $("#sellerProfileTriggerId").attr("href");

    var attrs = [];
     $("#prodDetails").find("tr").each(function(e){
        var attrKey = $(this).find("th").html();
        var attrValue = $(this).find("td").html();
        var attr = {};
        attr.key = attrKey;
        attr.value = attrValue;
        attrs.push(attr);
    })
    if(attrs.length==0){
        $("#detailBullets_feature_div").find(".a-list-item").each(function(e){
            var attrKey = $(this).find("span").html();
            var attrValue = $(this).find("span:eq(1)").html();
            var attr = {};
            attr.key = attrKey;
            attr.value = attrValue;
            attrs.push(attr);
        })
    }
    dataPro.title = $("#productTitle").html();
    dataPro.price = $(".a-price-whole").html()
    dataPro.attrs = attrs;
    dataPro.path = location.href;
    dataPro.cate = $("#my_cat_select").val();
    console.log(dataPro);

    $.post("https://www.gongrenbao.cn/index.php?c=api/ozon/updateaamazondetailpick",
          {dataPro:dataPro},
          function(data){
             var dataRes = JSON.parse(data);
             console.log(dataRes);
             if(dataRes.errorCode==0){
                alert("采集成功");
             }else{
                alert(dataRes.errorMsg);
             }
          },
      "text");

}



function setCookie(name, value, expires) {
    let cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

  if (expires) {
      const date = new Date();
      date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
      cookie += '; expires=' + date.toUTCString();
  }

      document.cookie = cookie + '; path=/';
}



function getCookie(name) {
  const cookies = ' ' + document.cookie;
  const search = ' ' + encodeURIComponent(name) + '=';

  let cookieValue = null;
  let offset = 0;

  while (offset < cookies.length) {
    let index = cookies.indexOf(search, offset);
    if (index === -1) {
      break;
    }

    index += search.length;
    let endIndex = cookies.indexOf(';', index);

    if (endIndex === -1) {
      endIndex = cookies.length;
    }

    cookieValue = decodeURIComponent(cookies.substring(index, endIndex));
    break;
  }

  return cookieValue;
}